// 数据库配置
const DB_NAME = 'LearningNotesDB';
const DB_VERSION = 1;
const NOTES_STORE = 'notes';

// 打开数据库
async function openDB() {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open(DB_NAME, DB_VERSION);
        
        request.onerror = () => {
            console.error('数据库打开失败:', request.error);
            reject(request.error);
        };
        
        request.onsuccess = () => {
            resolve(request.result);
        };
        
        request.onupgradeneeded = (event) => {
            const db = event.target.result;
            
            // 创建笔记存储
            if (!db.objectStoreNames.contains(NOTES_STORE)) {
                const store = db.createObjectStore(NOTES_STORE, { keyPath: 'id', autoIncrement: true });
                store.createIndex('title', 'title', { unique: false });
                store.createIndex('tags', 'tags', { unique: false, multiEntry: true });
                store.createIndex('createdAt', 'createdAt', { unique: false });
            }
        };
    });
}

// 存储API
const storage = {
    // 获取所有笔记
    async getAllNotes() {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction([NOTES_STORE], 'readonly');
            const store = transaction.objectStore(NOTES_STORE);
            const request = store.getAll();
            
            request.onsuccess = () => {
                resolve(request.result.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)));
            };
            
            request.onerror = () => reject(request.error);
        });
    },
    
    // 添加笔记
    async addNote(note) {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction([NOTES_STORE], 'readwrite');
            const store = transaction.objectStore(NOTES_STORE);
            
            const noteData = {
                ...note,
                createdAt: note.createdAt || new Date().toISOString(),
                updatedAt: new Date().toISOString()
            };
            
            const request = store.add(noteData);
            
            request.onsuccess = () => {
                resolve(request.result);
            };
            
            request.onerror = () => reject(request.error);
        });
    },
    
    // 更新笔记
    async updateNote(note) {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction([NOTES_STORE], 'readwrite');
            const store = transaction.objectStore(NOTES_STORE);
            
            const noteData = {
                ...note,
                updatedAt: new Date().toISOString()
            };
            
            const request = store.put(noteData);
            
            request.onsuccess = () => {
                resolve(request.result);
            };
            
            request.onerror = () => reject(request.error);
        });
    },
    
    // 删除笔记
    async deleteNote(id) {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction([NOTES_STORE], 'readwrite');
            const store = transaction.objectStore(NOTES_STORE);
            const request = store.delete(id);
            
            request.onsuccess = () => resolve();
            request.onerror = () => reject(request.error);
        });
    },
    
    // 获取单个笔记
    async getNote(id) {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const transaction = db.transaction([NOTES_STORE], 'readonly');
            const store = transaction.objectStore(NOTES_STORE);
            const request = store.get(id);
            
            request.onsuccess = () => {
                resolve(request.result);
            };
            
            request.onerror = () => reject(request.error);
        });
    },
    
    // 搜索笔记
    async searchNotes(query) {
        const notes = await this.getAllNotes();
        const lowerQuery = query.toLowerCase();
        
        return notes.filter(note => 
            note.title.toLowerCase().includes(lowerQuery) ||
            note.content.toLowerCase().includes(lowerQuery) ||
            note.tags.some(tag => tag.toLowerCase().includes(lowerQuery))
        );
    },
    
    // 按标签筛选
    async getNotesByTag(tag) {
        const notes = await this.getAllNotes();
        return notes.filter(note => note.tags.includes(tag));
    },
    
    // 获取所有标签
    async getAllTags() {
        const notes = await this.getAllNotes();
        const tags = new Set();
        
        notes.forEach(note => {
            note.tags.forEach(tag => tags.add(tag));
        });
        
        return Array.from(tags).sort();
    },
    
    // 导出数据
    async exportData() {
        const notes = await this.getAllNotes();
        return {
            notes,
            exportDate: new Date().toISOString(),
            version: '1.0'
        };
    },
    
    // 导入数据
    async importData(data) {
        if (!data.notes || !Array.isArray(data.notes)) {
            throw new Error('无效的数据格式');
        }
        
        const db = await openDB();
        const transaction = db.transaction([NOTES_STORE], 'readwrite');
        const store = transaction.objectStore(NOTES_STORE);
        
        // 清空现有数据
        await new Promise((resolve, reject) => {
            const clearRequest = store.clear();
            clearRequest.onsuccess = () => resolve();
            clearRequest.onerror = () => reject(clearRequest.error);
        });
        
        // 导入新数据
        for (const note of data.notes) {
            await new Promise((resolve, reject) => {
                const addRequest = store.add(note);
                addRequest.onsuccess = () => resolve();
                addRequest.onerror = () => reject(addRequest.error);
            });
        }
    }
};

// 全局暴露存储API
window.storage = storage;